package com.atguigu.gmall.payment.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.service.AliPayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wk
 * @create 2021-09-14 18:16
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    // 通过配置类配置商户信息后注入
    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String submit(Long orderId) {
        // 1.创建支付表 共用的 可以用来财务记账
        PaymentInfo paymentInfo = paymentInfoService.create(orderId, PaymentType.ALIPAY);
        // 2.和支付宝交互 统一收单交易创建接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(paymentInfo.getOutTradeNo());
        model.setTotalAmount(paymentInfo.getTotalAmount().toString());
        model.setSubject(paymentInfo.getSubject());
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setBody(paymentInfo.getSubject());
        model.setQrPayMode("1");
        model.setQrcodeWidth(100L);
        request.setBizModel(model);
        AlipayTradePagePayResponse response = null;
        try {
            // 发送请求
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }
}
